import java.util.ArrayList;
import java.util.List;

public class Test45 {
    public static int lastRemaining(int n ,int m){
        if (n < 1 || m< 1)  return -1;
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i< n;i++){
            list.add(i);
        }
        //要删除的位置
        int index = 0;
        int start = 0;//开始的位置
        while (list.size() > 1){
            //移动m-1次就到了要删除的点
            for (int i = 1;i<m;i++){
                index = (index+1)%list.size();
            }
            list.remove(index);
        }
        return list.get(0);
    }
    public static int lastRemaining2(int n,int m){
        if (n < 1 || m< 1)  return -1;
        int last = 0;
        for (int i = 2; i<=n;i++){
            last = (last+m)%i;
        }
        return last;
    }

    public static void main(String[] args) {
        System.out.println(lastRemaining(5, 3)); // 最后余下3
        System.out.println(lastRemaining(5, 2)); // 最后余下2
        System.out.println(lastRemaining(6, 7)); // 最后余下4
        System.out.println(lastRemaining(6, 6)); // 最后余下3
        System.out.println(lastRemaining(0, 0)); // 最后余下-1
        System.out.println("--------------");
        System.out.println(lastRemaining2(5, 3)); // 最后余下3
        System.out.println(lastRemaining2(5, 2)); // 最后余下2
        System.out.println(lastRemaining2(6, 7)); // 最后余下4
        System.out.println(lastRemaining2(6, 6)); // 最后余下3
        System.out.println(lastRemaining2(0, 0)); // 最后余下-1
    }
}
